package com.github.cloud.controller;

import com.github.cloud.common.util.Assert;
import com.github.cloud.common.util.R;
import com.github.cloud.common.util.SecurityConstants;
import com.github.cloud.service.SysUserService;
import com.google.code.kaptcha.Producer;
import com.xiaoleilu.hutool.io.IoUtil;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * Created by guxiaowei on 2018/3/8.
 * 验证码提供
 */
@RestController
public class ValidateCodeController {

    private static final Log log = LogFactory.get();

    @Autowired
    private Producer producer;

    @Autowired
    private SysUserService sysUserService;


    /***
     * 生成图片验证码
     * @param randomStr
     * @param request
     * @param response
     * @throws Exception
     */

    @GetMapping(SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX + "/{randomStr}")
    public void createCode(@PathVariable String randomStr, HttpServletRequest request, HttpServletResponse response) throws Exception {

        Assert.isBlank(randomStr,"随机码不能为空");
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        log.info("验证码:{}", text);
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        sysUserService.saveImageCode(randomStr, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "JPEG", out);
        IoUtil.close(out);
    }

    /**
     * 发送手机验证码
     * 后期要加接口限制
     *
     * @param mobile 手机号
     * @return R
     */
    @ResponseBody
    @GetMapping(SecurityConstants.MOBILE_VALIDATE_CODE_URL_PREFIX + "/{mobile}")
    public R<Boolean> createCode(@PathVariable String mobile) {
        Assert.isBlank(mobile, "手机号不能为空");
        return sysUserService.sendSmsCode(mobile);
    }
}
